// 项目基础layout布局
import { memo, useEffect, useState } from 'react'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { Layout, Menu, theme, Breadcrumb, Space, ConfigProvider, FloatButton, Tooltip, Table } from 'antd';
import { CloudOutlined, LogoutOutlined, FolderOutlined, EditOutlined, TableOutlined, FileOutlined, HomeOutlined } from '@ant-design/icons';
import { MemoAddNewFile } from '@/components/AddNewFile';
import { UploadFile } from '@/components/UploadFile';
import { MemoSearch } from '@/components/Search';
import { MemoMenu } from '@/components/Menu'
import { useMessage } from '@/hooks/useMessage';
import style from './index.module.css'
import { useSelector, useDispatch } from 'react-redux';
import { request } from '@/utils';  // 页面开始前初始化store，不可删，需要在引入store前引入
import { showMessage } from '@/store/modules/message';
import { clearUserInfo } from '@/store/modules/user';
import { clearToken } from '@/utils';
import { useParams } from 'react-router-dom';
import { getLayer, getFolderTree } from '@/apis/folder'
import { previewFile } from '@/apis/file';
import { searchRecentVisitDoc, searchDocByName, searchRecentlyAccessDocByDocName } from './api';
import { useTableColumns } from '@/views/DocList/pages/list/fields';
import { FILE_STATUS, formatDate } from '@/utils';
import JoinCollaborationBtn from './component/JoinCollaborationBtn';
import { debounce, throttle } from '@/utils/debounceThrottle';
import { useMemo } from 'react';

// 引入antd布局组件
const { Content, Sider } = Layout;

const Home = () => {
    // 主题token
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();

    const dispatch = useDispatch();
    const navigate = useNavigate()
    const location = useLocation()
    const param = useParams()

    // 面包屑数据
    const [folderLayer, setFolderLayer] = useState([])
    // 侧边栏树结构（暂未用到）
    const [folderTree, SetFolderTree] = useState([])
    // 侧边栏收起状态
    const [collapsed, setCollapsed] = useState(false);
    // redux消息
    const { message, type, visible } = useSelector(state => state.message)
    // 自定义消息hook
    const { success, error, contextHolder } = useMessage()
    // 最近访问文件列表
    const [recentList, setRecentList] = useState([]);
    // 搜索状态
    const [isSearching, setIsSearching] = useState(false);

    // 退出登录
    const exit = () => {
        dispatch(showMessage({ message: '退出成功', type: 'success' }))
        dispatch(clearUserInfo())
        clearToken()
        navigate('/login')
    }

    // 操作列点击事件
    const handleMenuClick = async (action, record) => {
        if (action === 'details') {
            try {
                // 调用接口查找文档
                const res = await searchDocByName({ name: record.name });
                if (res && res.code === 200 && res.data && res.data.length > 0) {
                    // 跳转到第一个匹配文档的详情页
                    navigate(`/docList/docDetail/${res.data[0].docId}`);
                } else {
                    error({ content: '未找到对应文档' });
                }
            } catch {
                error({ content: '查询文档失败' });
            }
        } else if (action === 'download') {
            preview(record.id);
        }
    };

    // 搜索功能
    const handleSearch = async (searchValue) => {
        if (!searchValue || searchValue.trim() === '') {
            // 如果搜索值为空，恢复显示最近访问文档
            setIsSearching(false);
            loadRecentVisitDoc();
            return;
        }

        setIsSearching(true);
        try {
            const res = await searchRecentlyAccessDocByDocName({ docName: searchValue.trim() });
            if (res && res.code === 200 && Array.isArray(res.data)) {
                // 将搜索结果转换为表格需要的格式
                const searchResults = res.data.map(item => ({
                    id: item.docId,
                    name: item.docName,
                    owner: item.ownerName,
                    updateTime: item.recentlyAccessTime,
                    status: FILE_STATUS['在线文档'],
                }));
                setRecentList(searchResults);
                
                // 更新面包屑
                setFolderLayer([
                    {
                        title: '最近访问文件',
                        onClick: () => {
                            setIsSearching(false);
                            loadRecentVisitDoc();
                        }
                    },
                    {
                        title: `搜索: ${searchValue}`,
                    }
                ]);
            } else {
                setRecentList([]);
                setFolderLayer([
                    {
                        title: '最近访问文件',
                        onClick: () => {
                            setIsSearching(false);
                            loadRecentVisitDoc();
                        }
                    },
                    {
                        title: `搜索: ${searchValue}`,
                    }
                ]);
            }
        } catch (err) {
            error({ content: '搜索失败，请重试' });
            setRecentList([]);
        }
    };

    // 加载最近访问文档
    const loadRecentVisitDoc = async () => {
        try {
            const res = await searchRecentVisitDoc();
            setRecentList(res.data.map(item => ({
                id: item.docId,
                name: item.docName,
                owner: item.ownerName,
                updateTime: item.recentlyAccessTime,
                status: FILE_STATUS['在线文档'],
            })));
            
            setFolderLayer([
                {
                    title: '最近访问文件',
                    onClick: () => navigate('/home')
                },
                ...res.data.map(item => ({
                    title: item.name,
                    onClick: () => navigate(`/home/list/${item.docId}`)
                }))
            ]);
        } catch (err) {
            setRecentList([]);
            setFolderLayer([
                {
                    title: '最近访问文件',
                }
            ]);
        }
    };

    // 获取表格列（与文档列表页一致）
    const { nameColumn, ownerColumn, updateTimeColumn, actionColumn } = useTableColumns(handleMenuClick);
    const columns = [
        { ...nameColumn, width: '30%' },
        { ...ownerColumn, width: '30%' },
        { ...updateTimeColumn, width: '30%' },
        {
            title: '操作',
            key: 'action',
            width: '10%',
            align: 'center',
            render: (_, record) => (
                <a onClick={() => throttledMenuClick('details', record)}>详情</a>
            ),
        }
    ];

    // 获取某一层级的面包屑
    const getLayerList = async (id) => {
        try {
            // const res = await getLayer(id)
            // let layer = res.data.reverse()
            setFolderLayer([
                {
                    title: '最近访问文件',
                    onClick: () => navigate('/home')
                },
                ...layer.map(item => ({
                    title: item.name,
                    onClick: () => navigate(`/home/list/${item.id}`)
                }))
            ])
        } catch {
            
        }
    }

    // 预览文件
    const preview = async (id) => {
        try {
            const res = await previewFile(id)
            window.open(res.data, '_blank')
        } catch {
            error({
                content: '下载文件失败，请检查网络'
            })
        }
    }


    useEffect(() => {
        if (param.id === undefined) {
            loadRecentVisitDoc();
        } else if (param.id) {
            getLayerList(param.id)
            setRecentList([])
        }
    }, [visible, message, type, param.id])

    // 点击文档名称跳转到详情页
    const handleClick = (record) => {
        navigate(`/docList/docDetail/${record.id}`);
    }

    // 侧边栏树结构相关（暂未启用）
    useEffect(() => {
        // getTree()
    }, [])

    // 路由刷新时（暂未启用）
    useEffect(() => {
        if (location.state?.refresh) {
        // getTree()
        }
            
    }, [location.state])

    // 防抖
    const debouncedHandleSearch = useMemo(() => debounce(handleSearch, 1000), [handleSearch]);
    const throttledMenuClick = useMemo(() => throttle(handleMenuClick, 1000), [handleMenuClick]);

    // 页面主渲染
    return (
        <Layout style={{
            height: '100vh',
        }}>
            {/* 全局消息提示 */}
            {contextHolder}
            {/* 右下角悬浮退出按钮 */}
            <FloatButton
                icon={<LogoutOutlined />}
                type='primary'
                onClick={exit}
                style={{
                    insetInlineEnd: 38,
                    insetBlockEnd: 100 
                }} />
            {/* 侧边栏 */}
            <Sider
                width={250}
                breakpoint="lg"
                collapsed={collapsed}
                onCollapse={setCollapsed}
                collapsedWidth={80}
                style={{
                    background: colorBgContainer,
                    overflowY: 'scroll',
                }}
                className={style.sider}
            >
                <div className={style.logo}>{collapsed ? <CloudOutlined style={{
                    fontSize: '25px',
                    color: '#1677ff'
                }} /> : 'CoDoc'}</div>
                <MemoMenu></MemoMenu>
            </Sider>
            {/* 右侧主内容区 */}
            <Layout
                style={{
                    padding: '0 24px 0',
                }}
            >
                <Content
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 280,
                        background: colorBgContainer,
                        borderRadius: borderRadiusLG,
                    }}
                >
                    {/* 面包屑 */}
                    <Breadcrumb separator=">" items={folderLayer}
                        style={{
                            fontSize: '24px'
                        }}
                        className={style.breadcrumb}
                    />
                    {/* 顶部操作区 */}
                    <ConfigProvider
                        wave={{
                            disabled: true, // 全局禁用波纹效果
                        }}
                    >
                         <Space size={50} style={{
                            marginTop: 20
                        }}>
                            <MemoAddNewFile></MemoAddNewFile>
                            <UploadFile></UploadFile>
                            <JoinCollaborationBtn />
                            <MemoSearch onSearch={debouncedHandleSearch}></MemoSearch>
                        </Space>
                    </ConfigProvider>
                    {/* 表格渲染 */}
                    {param.id === undefined && (
                        <Table
                            columns={columns}
                            dataSource={recentList.map(item => ({
                                ...item,
                                key: `${item.id}${item.status}`,
                                updateTime: formatDate(item.updateTime),
                            }))}
                            pagination={{ pageSize: 10 }}
                            scroll={{ y: 'calc(100vh - 260px)' }}
                            className={style.fileList}
                            tableLayout="fixed"
                        />
                    )}
                    {/* 子路由内容区 */}
                    <div
                        style={{
                            background: colorBgContainer,
                            borderRadius: borderRadiusLG,
                        }}
                        className={style.fileList}
                    >
                    </div>
                </Content>
            </Layout>
        </Layout >
    )
}

export const MemoHome = memo(Home)